<template>
    <div class="escort-container">
      <!-- 顶部导航 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="预约托管" name="booking"></el-tab-pane>
        <el-tab-pane label="课程安排" name="course"></el-tab-pane>
        <el-tab-pane label="孩子动态" name="dynamic"></el-tab-pane>
      </el-tabs>
  
      <!-- 预约托管面板 -->
      <div v-if="activeTab === 'booking'" class="booking-panel">
        <el-form :model="bookingForm" label-width="120px">
          <el-form-item label="孩子姓名" required>
            <el-input v-model="bookingForm.childName" placeholder="请输入孩子姓名" />
          </el-form-item>
          <el-form-item label="所在学校" required>
            <el-input v-model="bookingForm.school" placeholder="请输入学校名称" />
          </el-form-item>
          <el-form-item label="班级" required>
            <el-input v-model="bookingForm.className" placeholder="请输入班级" />
          </el-form-item>
          <el-form-item label="接送时间" required>
            <el-date-picker
              v-model="bookingForm.escortTime"
              type="datetime"
              placeholder="选择接送时间"
            />
          </el-form-item>
          <el-form-item label="接送地点" required>
            <el-input v-model="bookingForm.escortAddress" placeholder="请输入接送地点" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitBooking">提交预约</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 预约记录 -->
        <div class="booking-list">
          <h3>我的预约记录</h3>
          <el-table :data="bookings" style="width: 100%">
            <el-table-column prop="childName" label="孩子姓名" width="120" />
            <el-table-column prop="school" label="学校" width="180" />
            <el-table-column prop="escortTime" label="接送时间" width="180">
              <template #default="{row}">
                {{ formatDateTime(row.escortTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{row}">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{row}">
                <el-button link @click="cancelBooking(row.bookingId)">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:current-page="bookingPage.current"
            v-model:page-size="bookingPage.size"
            :total="bookingPage.total"
            layout="total, prev, pager, next"
            @current-change="fetchBookings"
          />
        </div>
      </div>
  
      <!-- 课程安排面板 -->
      <div v-if="activeTab === 'course'" class="course-panel">
        <el-timeline>
          <el-timeline-item
            v-for="course in courses"
            :key="course.courseId"
            :timestamp="formatDateTime(course.startTime) + ' - ' + formatTime(course.endTime)"
            placement="top"
          >
            <el-card>
              <h4>{{ course.name }}</h4>
              <p>{{ course.description }}</p>
              <div class="course-meta">
                <span>授课老师: {{ course.teacher }}</span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
  
      <!-- 孩子动态面板 -->
      <div v-if="activeTab === 'dynamic'" class="dynamic-panel">
        <div class="dynamic-list">
          <div v-for="item in dynamics" :key="item.dynamicId" class="dynamic-item">
            <div class="dynamic-header">
              <span class="child-name">{{ item.childName }}</span>
              <span class="create-time">{{ formatDateTime(item.createTime) }}</span>
            </div>
            <div class="dynamic-content">
              {{ item.content }}
            </div>
            <div v-if="item.images" class="dynamic-images">
              <el-image
                v-for="(img, index) in getImageList(item.images)"
                :key="index"
                :src="img"
                :preview-src-list="getImageList(item.images)"
                fit="cover"
                class="dynamic-image"
              />
            </div>
          </div>
        </div>
        <el-pagination
          v-model:current-page="dynamicPage.current"
          v-model:page-size="dynamicPage.size"
          :total="dynamicPage.total"
          layout="total, prev, pager, next"
          @current-change="fetchDynamics"
        />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import dayjs from 'dayjs'
  
  /**
   * 当前激活的标签页
   * @type {import('vue').Ref<'booking'|'course'|'dynamic'>}
   */
  const activeTab = ref('booking')
  
  /**
   * 预约表单数据
   * @type {import('vue').Ref<{
   *   childName: string,
   *   school: string,
   *   className: string,
   *   escortTime: Date,
   *   escortAddress: string
   * }>}
   */
  const bookingForm = ref({
    childName: '',
    school: '',
    className: '',
    escortTime: null,
    escortAddress: ''
  })
  
  /**
   * 预约记录分页数据
   * @type {import('vue').Ref<{
   *   current: number,
   *   size: number,
   *   total: number
   * }>}
   */
  const bookingPage = ref({
    current: 1,
    size: 10,
    total: 0
  })
  
  /**
   * 动态记录分页数据
   * @type {import('vue').Ref<{
   *   current: number,
   *   size: number,
   *   total: number
   * }>}
   */
  const dynamicPage = ref({
    current: 1,
    size: 10,
    total: 0
  })
  
  /**
   * 预约记录列表
   * @type {import('vue').Ref<Array<{
   *   bookingId: number,
   *   childName: string,
   *   school: string,
   *   className: string,
   *   escortTime: string,
   *   escortAddress: string,
   *   status: number,
   *   createTime: string
   * }>>}
   */
  const bookings = ref([])
  
  /**
   * 课程安排列表
   * @type {import('vue').Ref<Array<{
   *   courseId: number,
   *   name: string,
   *   description: string,
   *   startTime: string,
   *   endTime: string,
   *   teacher: string
   * }>>}
   */
  const courses = ref([])
  
  /**
   * 孩子动态列表
   * @type {import('vue').Ref<Array<{
   *   dynamicId: number,
   *   childName: string,
   *   content: string,
   *   images: string,
   *   createTime: string
   * }>>}
   */
  const dynamics = ref([])
  
  /**
   * 初始化数据
   */
  onMounted(() => {
    fetchBookings()
    fetchCourses()
    fetchDynamics()
  })
  
  /**
   * 标签页切换处理
   * @param {string} tabName - 切换到的标签页名称
   */
  const handleTabChange = (tabName) => {
    activeTab.value = tabName
  }
  
  /**
   * 提交托管预约
   */
  const submitBooking = async () => {
    if (!validateBookingForm()) return
    
    try {
      // 模拟API调用
      const newBooking = {
        ...bookingForm.value,
        bookingId: Date.now(),
        status: 0,
        createTime: new Date().toISOString()
      }
      
      bookings.value.unshift(newBooking)
      ElMessage.success('预约成功')
      resetBookingForm()
    } catch (error) {
      ElMessage.error('预约失败: ' + error.message)
    }
  }
  
  /**
   * 验证预约表单
   * @returns {boolean} 是否验证通过
   */
  const validateBookingForm = () => {
    if (!bookingForm.value.childName) {
      ElMessage.warning('请输入孩子姓名')
      return false
    }
    if (!bookingForm.value.escortTime) {
      ElMessage.warning('请选择接送时间')
      return false
    }
    return true
  }
  
  /**
   * 重置预约表单
   */
  const resetBookingForm = () => {
    bookingForm.value = {
      childName: '',
      school: '',
      className: '',
      escortTime: null,
      escortAddress: ''
    }
  }
  
  /**
   * 获取预约记录
   */
  const fetchBookings = async () => {
    try {
      // 模拟API调用
      const mockData = generateMockBookings()
      bookings.value = mockData
      bookingPage.value.total = 35 // 模拟总条数
    } catch (error) {
      ElMessage.error('获取预约记录失败: ' + error.message)
    }
  }
  
  /**
   * 获取课程安排
   */
  const fetchCourses = async () => {
    try {
      // 模拟API调用
      const mockData = generateMockCourses()
      courses.value = mockData
    } catch (error) {
      ElMessage.error('获取课程安排失败: ' + error.message)
    }
  }
  
  /**
   * 获取孩子动态
   */
  const fetchDynamics = async () => {
    try {
      // 模拟API调用
      const mockData = generateMockDynamics()
      dynamics.value = mockData
      dynamicPage.value.total = 28 // 模拟总条数
    } catch (error) {
      ElMessage.error('获取动态失败: ' + error.message)
    }
  }
  
  /**
   * 取消预约
   * @param {number} bookingId - 预约ID
   */
  const cancelBooking = async (bookingId) => {
    try {
      // 模拟API调用
      bookings.value = bookings.value.filter(item => item.bookingId !== bookingId)
      ElMessage.success('已取消预约')
    } catch (error) {
      ElMessage.error('取消预约失败: ' + error.message)
    }
  }
  
  /**
   * 处理图片字符串为数组
   * @param {string} images - 图片字符串(逗号分隔)
   * @returns {string[]} 图片URL数组
   */
  const getImageList = (images) => {
    if (!images) return []
    return images.split(',').map(img => img.trim())
  }
  
  /**
   * 格式化日期时间
   * @param {string} dateTime - ISO格式日期时间字符串
   * @returns {string} 格式化后的日期时间
   */
  const formatDateTime = (dateTime) => {
    return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
  }
  
  /**
   * 格式化时间
   * @param {string} dateTime - ISO格式日期时间字符串
   * @returns {string} 格式化后的时间
   */
  const formatTime = (dateTime) => {
    return dayjs(dateTime).format('HH:mm')
  }
  
  /**
   * 获取状态标签类型
   * @param {number} status - 状态码
   * @returns {string} 标签类型
   */
  const getStatusTagType = (status) => {
    const types = ['info', 'success', 'warning']
    return types[status] || 'info'
  }
  
  /**
   * 获取状态文本
   * @param {number} status - 状态码
   * @returns {string} 状态文本
   */
  const getStatusText = (status) => {
    const texts = ['待确认', '已确认', '已完成']
    return texts[status] || '未知'
  }
  
  /**
   * 生成模拟预约数据
   * @returns {Array} 模拟预约数据
   */
  const generateMockBookings = () => {
    return [
      {
        bookingId: 1,
        childName: '张三',
        school: '第一实验小学',
        className: '三年级二班',
        escortTime: new Date(Date.now() + 86400000).toISOString(),
        escortAddress: '学校正门',
        status: 0,
        createTime: new Date().toISOString()
      },
      {
        bookingId: 2,
        childName: '李四',
        school: '阳光小学',
        className: '一年级一班',
        escortTime: new Date(Date.now() + 172800000).toISOString(),
        escortAddress: '学校东门',
        status: 1,
        createTime: new Date(Date.now() - 86400000).toISOString()
      }
    ]
  }
  
  /**
   * 生成模拟课程数据
   * @returns {Array} 模拟课程数据
   */
  const generateMockCourses = () => {
    return [
      {
        courseId: 1,
        name: '课后作业辅导',
        description: '帮助孩子完成当天作业，解答疑难问题',
        startTime: new Date(Date.now() + 3600000 * 16).toISOString(),
        endTime: new Date(Date.now() + 3600000 * 17).toISOString(),
        teacher: '王老师'
      },
      {
        courseId: 2,
        name: '美术创作',
        description: '培养孩子艺术创造力，学习基础绘画技巧',
        startTime: new Date(Date.now() + 86400000 + 3600000 * 15).toISOString(),
        endTime: new Date(Date.now() + 86400000 + 3600000 * 16).toISOString(),
        teacher: '李老师'
      }
    ]
  }
  
  /**
   * 生成模拟动态数据
   * @returns {Array} 模拟动态数据
   */
  const generateMockDynamics = () => {
    return [
      {
        dynamicId: 1,
        childName: '张三',
        content: '今天完成了数学作业，表现很好，还帮助了其他同学',
        images: 'https://picsum.photos/300/200?random=1,https://picsum.photos/300/200?random=2',
        createTime: new Date().toISOString()
      },
      {
        dynamicId: 2,
        childName: '李四',
        content: '参加了美术课，创作了一幅美丽的风景画',
        images: 'https://picsum.photos/300/200?random=3',
        createTime: new Date(Date.now() - 86400000).toISOString()
      }
    ]
  }
  </script>
  
  <style scoped>
  .escort-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .booking-panel {
    margin-top: 20px;
  }
  
  .booking-list {
    margin-top: 40px;
  }
  
  .course-panel {
    margin-top: 20px;
  }
  
  .dynamic-panel {
    margin-top: 20px;
  }
  
  .dynamic-item {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }
  
  .dynamic-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
  }
  
  .child-name {
    font-weight: bold;
  }
  
  .create-time {
    color: #909399;
  }
  
  .dynamic-content {
    margin-bottom: 10px;
    line-height: 1.6;
  }
  
  .dynamic-images {
    display: flex;
    gap: 10px;
  }
  
  .dynamic-image {
    width: 100px;
    height: 100px;
    border-radius: 4px;
  }
  
  .course-meta {
    margin-top: 10px;
    font-size: 14px;
    color: #909399;
  }
  </style>